package com.test.ayi.service;

import com.sun.mail.imap.IMAPStore;

import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import java.util.HashMap;
import java.util.Properties;

public class EmailReceiver {
    public static void main(String[] args) {
        // 邮箱配置
        String host = "imap.126.com"; // 126邮箱的IMAP服务器地址
        String username = "chenglongyiyiyi@126.com"; // 邮箱地址
        String password = "PMgL7mhCJmWxame6"; // 授权码

        // 配置IMAP属性
        Properties properties = new Properties();
        properties.put("mail.store.protocol", "imap");
        properties.put("mail.imap.host", host);
        properties.put("mail.imap.port", "993");
        //properties.put("mail.imap.ssl.enable", "true");

        HashMap IAM = new HashMap();
//带上IMAP ID信息，由key和value组成，例如name，version，vendor，support-email等。
        IAM.put("name","myname");
        IAM.put("version","1.0.0");
        IAM.put("vendor","myclient");
        IAM.put("support-email","testmail@test.com");

        try {
            Session session = Session.getInstance(properties);
            IMAPStore store = (IMAPStore) session.getStore("imap");
//下方替换对应帐号和授权码
            store.connect("chenglongyiyiyi@126.com", "PMgL7mhCJmWxame6");
            store.id(IAM);

            // 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            // 获取邮件
            Message[] messages = inbox.getMessages();
            int count = messages.length;

            // 读取最新的3封邮件
            for (int i = count - 1; i >= Math.max(0, count - 3); i--) {
                Message message = messages[i];
                String subject = message.getSubject();
                String content = getTextFromMessage(message);

                System.out.println("邮件标题: " + subject);
                System.out.println("邮件内容: " + content);
                System.out.println("-------------------------");
            }

            // 关闭连接
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 提取邮件内容
    private static String getTextFromMessage(Message message) throws Exception {
        if (message.isMimeType("text/plain")) {
            return message.getContent().toString();
        } else if (message.isMimeType("multipart/*")) {
            MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < mimeMultipart.getCount(); i++) {
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                if (bodyPart.isMimeType("text/plain")) {
                    result.append(bodyPart.getContent());
                }
            }
            return result.toString();
        }
        return "";
    }
}